import axios from "axios";
import store from "@/store";
import { ElMessage } from "element-plus";

const service = axios.create({
  baseURL: "/springbootsiiny4vh",
  timeout: 10000,
  withCredentials: true,
  headers: {
    "Content-Type": "application/json; charset=utf-8",
  },
});

// 请求拦截器
service.interceptors.request.use(
  (config) => {
    // 在这个位置需要统一的去注入token
    if (store.getters.token) {
      // 如果token存在 注入token
      // config.headers.Authorization = `Bearer ${store.getters.token}`;
      config.headers["Token"] = store.getters.token; // 请求头带上token
    }
    return config; // 必须返回配置
  },
  (error) => {
    return Promise.reject(error);
  }
);
// 响应拦截器
service.interceptors.response.use(
  // 请求成功
  (response) => {
    const { code, msg } = response.data;
    const data = response.data;

    // 根据success的成功与否来决定下面的操作
    if (code == 0) {
      return data;
    } else {
      ElMessage.error(msg);
      return Promise.reject(new Error(msg));
    }
  },
  // 请求失败
  (error) => {
    // TODO：将来处理token超时问题
    ElMessage.error(error);
    return Promise.reject(error);
  }
);

export default service;
